package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysLogDao;
import com.cy.pj.sys.pojo.PageObject;
import com.cy.pj.sys.pojo.SysLog;
import com.cy.pj.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class SysLogServiceImpl implements SysLogService {
    @Autowired
    private SysLogDao sysLogDao;

    @RequiredLog("日志查询")
    @Override
    public PageObject<SysLog> findPageObjects(String username, Integer pageCurrent)  {
        if(pageCurrent==null||pageCurrent<1){
            throw new IllegalArgumentException("当前页码不正确");
        }
        //查询
        int rowCount=sysLogDao.getRowCount(username);
        //验证是否为0
        if(rowCount==0){
            throw new ServiceException("系统没找到对应记录");
        }
        //基于条件查询当前页记录
        int pageSize=5;
        int startIndex=(pageCurrent-1)*pageSize;
        List<SysLog> records=sysLogDao.findPageObjects(username,startIndex,pageSize);
        //对当前页记录封装
        PageObject<SysLog> pageObject=new PageObject<>();
        //封装数据(用构造方法封装)
//        pageObject.setPageSize(pageSize);
//        pageObject.setRowCount(rowCount);
//        pageObject.setRecords(records);
//        pageObject.setPageCount((rowCount-1)/pageSize+1);
        //返回封装结果
        return new PageObject<>(pageCurrent,pageSize,rowCount,records);
    }

    @RequiresPermissions("sys:log:delete")
    @RequiredLog("日志删除")
    @Override
    public int deleteObjects(Integer... ids) {
        if(ids==null||ids.length==0){
            throw new IllegalArgumentException("请选择一个");
        }
        int rows;
        try {
            rows=sysLogDao.deleteObjects(ids);
        }catch (Throwable e){
            e.printStackTrace();
            throw new ServiceException("系统故障，正在恢复中...");
        }
        if(rows==0){throw new ServiceException("记录可能已经不存在");}
        return rows;
    }

    @Async
    @Transactional
    @Override
    public void saveObject(SysLog entity) {
        String tName=Thread.currentThread().getName();
        System.out.println("saveObject->thread.name->"+tName);
        try {
            Thread.sleep(5000);
        }catch (Exception e){
        }
        sysLogDao.insertObject(entity);
    }
}
